package com.example.demo01.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录检查: 会拦截几乎所有的请求(包括错误的路径请求)，如果没有登录，直接转发到 login.html
 *
 * @author wangxun
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Object loginUser = request.getSession().getAttribute("loginUser");

        if (loginUser == null) {
            // TODO: 未登录，返回登录页面
            request.setAttribute("msg", "没有权限请先登录");
            request.getRequestDispatcher("/login.html").forward(request, response);
            return false;
        } else {
            // TODO: 已登录
            return true;
        }
    }
}
